/*
 * @Author: 缄默
 * @Date: 2022-05-24 20:18:42
 * @LastEditors: 缄默
 * @LastEditTime: 2022-05-24 21:06:25
 */

//反转字符串

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    //反转字符串1
    void rotateWord1(vector<char>& chas) {
        if (chas.size() == 0) {
            return ;
        }
        reverse(chas, 0, chas.size() - 1);
        int left = 0;
        int right = -1;
        for (int i = 0; i < chas.size(); i++) {
            if (chas[i] == ' ') {
                right = i - 1;
                reverse(chas, left, right);
                left = i + 1;
            }
        }
        right = chas.size() - 1;
        reverse(chas, left, right);
        return ;
    }

    void rotate2(vector<char>& chas, int size) {
        if (chas.size() == 0 || size <= 0 || size >= chas.size()) { return ;}
        int start = 0;
        int end = chas.size() - 1;
        int lpart = size;
        int rpart = chas.size() - size;
        int s = min(lpart, rpart);
        int d = lpart - rpart;
        while (true) {
            exchange(chas, start, end, s);
            if (d == 0) {
                break;
            } else if (d > 0) {
                start += s;
                lpart = d;
            } else {
                end -= s;
                rpart = -d;
            }
            s = min(lpart, rpart);
            d = lpart - rpart;
        }

    }
    //打印chas
    void printChas(vector<char>& chas) {
        for (auto ch : chas) {
            cout << ch;
        }
        cout << endl;
        return ;
    }

private:
    //反转left到right范围内的字符串
    void reverse(vector<char>& chas, int left, int right) {
        char temp;
        for (int i = left, j = right; i < j; i++) {
            temp = chas[j];
            chas[j] = chas[i];
            chas[i] = temp;
            j--;    
        }
        return ;

    }

    void exchange(vector<char>& chas, int start, int end, int s) {
        int i = end - s + 1;
        char tmp = 0;
        while (s-- != 0) {
            tmp = chas[start];
            chas[start] = chas[i];
            chas[i] = tmp;
            start++;
            i++;
        }
    }
};

int main() {
    char charInit[20] = {"dog love pig"};
    vector<char> chas(charInit, charInit + 12);
    Solution solu;
    solu.printChas(chas);
    solu.rotateWord1(chas);
    solu.printChas(chas);
    char charInit2[20] = {"1234567ABCD"};
    vector<char> chas2(charInit2, charInit2 + 11);
    solu.rotate2(chas2, 7);
    solu.printChas(chas2);
    return 0;
}



